package vip.xiaonuo.h5.royalty.modular.order.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.h5.royalty.modular.order.param.OrderListParam;
import vip.xiaonuo.h5.royalty.modular.order.param.OrderDetailParam;
import vip.xiaonuo.h5.royalty.modular.order.service.OrderService;
import vip.xiaonuo.h5.royalty.modular.order.vo.OrderPage;
import vip.xiaonuo.h5.royalty.modular.order.vo.OrderDetailVo;
import vip.xiaonuo.h5.royalty.modular.order.vo.OrderVo;
import vip.xiaonuo.h5.royalty.system.profitsharecreditrecord.entity.H5ProfitShareCreditRecord;
import vip.xiaonuo.h5.royalty.system.profitsharecreditrecord.service.H5ProfitShareCreditRecordService;
import vip.xiaonuo.h5.royalty.system.record.entity.H5Record;
import vip.xiaonuo.h5.royalty.system.record.service.H5RecordService;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private H5ProfitShareCreditRecordService h5ProfitShareCreditRecordService;

    @Autowired
    private H5RecordService h5RecordService;

    /**
     * 获取订单列表
     * @param param 查询参数
     * @return 订单列表
     */
    @Override
    public OrderPage getOrderList(OrderListParam param) {
        // 获取当前登录用户ID
        String loginUserId = StpUtil.getLoginIdAsString();

        // 构建查询条件
        LambdaQueryWrapper<H5ProfitShareCreditRecord> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询当前用户的分润记录
        queryWrapper.eq(H5ProfitShareCreditRecord::getSharePartyId, loginUserId);

        // 按场站筛选
        if (ObjUtil.isNotEmpty(param.getStationId())) {
            queryWrapper.eq(H5ProfitShareCreditRecord::getStationId, param.getStationId());
        }

        // 按时间范围筛选（日期字段）
        if (ObjUtil.isNotEmpty(param.getStartTime()) && ObjUtil.isNotEmpty(param.getEndTime())) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date startDate = sdf.parse(param.getStartTime());
                Date endDate = sdf.parse(param.getEndTime());

                queryWrapper.ge(H5ProfitShareCreditRecord::getCreditDate, startDate)
                            .le(H5ProfitShareCreditRecord::getCreditDate, endDate);
            } catch (Exception e) {
                log.error("日期格式转换错误：{}", e.getMessage());
            }
        }

        // 先查询总记录数（不包含分页条件）
        long totalCount = h5ProfitShareCreditRecordService.count(queryWrapper);

        // 按lastId分页（适用于无限滚动）
        if (ObjUtil.isNotEmpty(param.getLastId())) {
            queryWrapper.lt(H5ProfitShareCreditRecord::getId, param.getLastId());
        }

        // 添加分页和排序条件
        queryWrapper.orderByDesc(H5ProfitShareCreditRecord::getCreateTime);
        queryWrapper.last("LIMIT 10");

        // 查询分润记录
        List<H5ProfitShareCreditRecord> profitRecords = h5ProfitShareCreditRecordService.list(queryWrapper);

        // 创建返回结果对象
        OrderPage result = new OrderPage();

        if (ObjUtil.isEmpty(profitRecords)) {
            result.setList(new ArrayList<>());
            result.setTotal((int) Math.min(totalCount, Integer.MAX_VALUE));
            // 初始化新增字段
            result.setTotalServiceFee(BigDecimal.ZERO);
            result.setTotalActualIncome(BigDecimal.ZERO);
            return result;
        }

        // 批量查询record信息
        Map<String, H5Record> recordMap = profitRecords.stream()
                .map(H5ProfitShareCreditRecord::getRecordId)
                .filter(ObjUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.collectingAndThen(
                        Collectors.toList(),
                        ids -> CollUtil.isNotEmpty(ids) ?
                                h5RecordService.listByIds(ids).stream()
                                        .collect(Collectors.toMap(H5Record::getId, record -> record)) :
                                new HashMap<>()
                ));

        // 转换为订单VO
        List<OrderVo> orderList = profitRecords.stream()
                .map(creditRecord -> {
                    OrderVo orderVo = new OrderVo();

                    // 设置基本信息
                    orderVo.setProfitOrderId(creditRecord.getId());
                    orderVo.setStationName(creditRecord.getStationName());


                    // 设置翻译ID
                    H5Record record = recordMap.get(creditRecord.getRecordId());
                    orderVo.setOrgId(creditRecord.getOrgId());
                    if (record != null) {
                        orderVo.setPileId(record.getPileId());
                        orderVo.setGunId(record.getGunId());
                    }

                    // 设置其他信息
                    if (ObjUtil.isNotEmpty(creditRecord.getCreditTime())) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        orderVo.setInComeTime(sdf.format(creditRecord.getCreditTime()));
                    }

                    orderVo.setServiceFeeTotal(creditRecord.getServiceFeeTotal());
                    orderVo.setActualIncome(creditRecord.getShareAmount());
                    orderVo.setShareRatio(creditRecord.getShareRatio());
                    orderVo.setOtherFee(new BigDecimal("0.00"));

                    return orderVo;
                })
                .collect(Collectors.toList());

        result.setList(orderList);
        result.setTotal((int) Math.min(totalCount, Integer.MAX_VALUE));

        // 计算新增字段的值
        BigDecimal totalServiceFee = BigDecimal.ZERO;
        BigDecimal totalActualIncome = BigDecimal.ZERO;

        for (OrderVo order : orderList) {
            // 累加总服务费
            if (order.getServiceFeeTotal() != null) {
                totalServiceFee = totalServiceFee.add(order.getServiceFeeTotal());
            }
            // 累加总实际收入
            if (order.getActualIncome() != null) {
                totalActualIncome = totalActualIncome.add(order.getActualIncome());
            }
        }

        // 设置新增字段的值，保留两位小数
        result.setTotalServiceFee(totalServiceFee.setScale(2, BigDecimal.ROUND_HALF_UP));
        result.setTotalActualIncome(totalActualIncome.setScale(2, BigDecimal.ROUND_HALF_UP));

        return result;
    }

    /**
     * 获取订单详情
     * @param param 订单详情参数
     * @return 订单详情
     */
    @Override
    public OrderDetailVo getOrderDetail(OrderDetailParam param) {
        // TODO: 实现订单详情查询逻辑
        return null;
    }

    /**
     * 取消订单
     * @param param 订单详情参数
     * @return 操作结果
     */
    @Override
    public Boolean cancelOrder(OrderDetailParam param) {
        // TODO: 实现订单取消逻辑
        return false;
    }

}
